<template>
  <view class="cart-page">
    <!-- 当购物车有商品时显示商品列表 -->
    <view v-if="groupedCartProducts.length > 0">
      <!-- 遍历每个店铺组 -->
      <view
        v-for="(shopGroup, shopIndex) in groupedCartProducts"
        :key="shopIndex"
        class="shop-group"
      >
        <!-- 店铺组头部，包含全选按钮和清空购物车按钮 -->
        <view class="header">
          <button
            @click="handleShopAllSelect(shopIndex)"
            :class="{ active: shopGroup.isAllSelected }"
          ></button>
          <span class="clear-cart" @click="clearShopCart(shopIndex)">清空购物车</span>
        </view>
        <!-- 显示店铺名称和总价 -->
        <div class="shop-name">
          {{ shopGroup.shopName }}
          <span class="shop-total-price">￥{{ shopGroup.totalPrice }}</span>
        </div>
        <!-- 遍历每个店铺下的商品 -->
        <view
          class="cart-item"
          v-for="(cartItem, itemIndex) in shopGroup.products"
          :key="itemIndex"
        >
          <!-- 商品单选按钮 -->
          <button
            @click="handleItemSelect(shopIndex, itemIndex)"
            :class="{ active: cartItem.isSelected }"
          ></button>
          <!-- 商品图片 -->
          <image
            :src="cartItem.imgUrl"
            :alt="cartItem.name"
            class="cart-item-image"
          ></image>
          <!-- 商品信息 -->
          <div class="cart-item-info">
            <!-- 商品名称和规格 -->
            <div class="cart-item-name">{{ cartItem.name }} {{ cartItem.specification }}</div>
            <!-- 商品价格信息 -->
            <div class="price-container">
              <span class="product-price">¥{{ cartItem.price }}</span>
              <span class="original-price" v-if="cartItem.oldPrice">¥{{ cartItem.oldPrice }}</span>
            </div>
            <!-- 商品数量调整区域 -->
            <div class="quantity-container">
              <button @click="decreaseQuantity(shopIndex, itemIndex)">-</button>
              <span class="cart-item-quantity">{{ cartItem.quantity }}</span>
              <button @click="increaseQuantity(shopIndex, itemIndex)">+</button>
            </div>
          </div>
        </view>
      </view>
      <!-- 总价和结算区域，有商品时显示 -->
      <view class="total-price-container" v-if="groupedCartProducts.length > 0">
        <span class="total-price-text">总计：<span style="color:red">{{ totalPrice }}￥</span> </span>
        <button class="settlement-button" @click="goToSettlement">结算</button>
      </view>
    </view>
    <!-- 当购物车无商品时显示提示信息 -->
    <view v-else class="empty-cart-tip">购物车空空如也</view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      groupedCartProducts: [],
      totalPrice: 0
    };
  },
  onLoad(options) {
    this.fetchCartData();
  },
  onShow() {
    this.fetchCartData();
  },
  created() {
    this.fetchCartData();
  },
  methods: {
    // 异步获取购物车数据
    async fetchCartData() {
      try {
        const timestamp = new Date().getTime();
        const response = await this.$axios.get(`http://localhost:3000/cart?_t=${timestamp}`);
        const cartData = response.data;
        const shopsObj = {};
        cartData.forEach((product) => {
          if (product.quantity > 0) {
            if (!shopsObj[product.shopId]) {
              shopsObj[product.shopId] = {
                shopName: '',
                isAllSelected: true,
                products: [],
                totalPrice: 0, // 初始化商铺总价
                selectedProductId: null
              };
            }
            const existingProduct = shopsObj[product.shopId].products.find((p) => p.id === product.id);
            if (existingProduct) {
              existingProduct.quantity += product.quantity;
            } else {
              shopsObj[product.shopId].products.push({...product, isSelected: true });
            }
          }
        });

        const shops = await this.$axios.get('http://localhost:3000/shops');
        Object.keys(shopsObj).forEach((shopId) => {
          const shop = shops.data.find((s) => s.id === shopId);
          if (shop) {
            shopsObj[shopId].shopName = shop.name;
          }
        });
        this.groupedCartProducts = Object.values(shopsObj);
        this.calculateTotalPrice();
      } catch (error) {
        console.error('获取购物车数据失败', error);
      }
    },
    // 处理单个商品选择事件
    handleItemSelect(shopIndex, itemIndex) {
      const product = this.groupedCartProducts[shopIndex].products[itemIndex];
      product.isSelected =!product.isSelected;

      // 检查该店铺的所有商品是否都被选中
      const allSelected = this.groupedCartProducts[shopIndex].products.every((p) => p.isSelected);
      this.groupedCartProducts[shopIndex].isAllSelected = allSelected;

      this.calculateTotalPrice();
    },
    // 处理店铺商品全选事件
    handleShopAllSelect(shopIndex) {
      const isAllSelected = this.groupedCartProducts[shopIndex].isAllSelected;
      this.groupedCartProducts[shopIndex].products.forEach((product) => {
        product.isSelected =!isAllSelected;
      });
      this.groupedCartProducts[shopIndex].isAllSelected =!isAllSelected;
      this.calculateTotalPrice();
    },
    // 异步清空指定店铺的购物车
    async clearShopCart(shopIndex) {
      const shopProducts = this.groupedCartProducts[shopIndex].products;
      for (let i = 0; i < shopProducts.length; i++) {
        const itemIndex = i;
        const product = shopProducts[itemIndex];
        product.quantity = 0;
        try {
          const response = await this.$axios.put(`http://localhost:3000/cart/${product.id}`, { quantity: 0 });
          console.log('商品数量已更新为0', response.data);
        } catch (error) {
          console.error('更新商品数量失败', error);
        }
      }
      await this.fetchCartData();
    },
    // 计算购物车总价
    calculateTotalPrice() {
      this.totalPrice = 0;
      this.groupedCartProducts.forEach((shopGroup) => {
        shopGroup.totalPrice = 0; // 重置每个商铺的总价
        shopGroup.products.forEach((product) => {
          if (product.isSelected) {
            const productPrice = product.quantity * product.price;
            this.totalPrice += productPrice;
            shopGroup.totalPrice += productPrice;
          }
        });
      });
    },
    // 增加商品数量
    async increaseQuantity(shopIndex, itemIndex) {
      const product = this.groupedCartProducts[shopIndex].products[itemIndex];
      product.quantity++;
      try {
        const response = await this.$axios.put(`http://localhost:3000/cart/${product.id}`, { quantity: product.quantity });
        console.log('商品数量已更新', response.data);
        this.calculateTotalPrice();
      } catch (error) {
        console.error('更新商品数量失败', error);
        product.quantity--;
      }
    },
    // 减少商品数量
    async decreaseQuantity(shopIndex, itemIndex) {
      const product = this.groupedCartProducts[shopIndex].products[itemIndex];
      product.quantity--;
      if (product.quantity === 0) {
        try {
          const response = await this.$axios.delete(`http://localhost:3000/cart/${product.id}`);
          console.log('商品已从购物车移除', response.data);
          this.groupedCartProducts[shopIndex].products = this.groupedCartProducts[shopIndex].products.filter((_, index) => index!== itemIndex);
        } catch (error) {
          console.error('移除商品失败', error);
          product.quantity++;
        }
      } else {
        try {
          const response = await this.$axios.put(`http://localhost:3000/cart/${product.id}`, { quantity: product.quantity });
          console.log('商品数量已更新', response.data);
        } catch (error) {
          console.error('更新商品数量失败', error);
          product.quantity++;
        }
      }
      this.calculateTotalPrice();
    },
    // 前往结算页面
    async goToSettlement() {
      const selectedProducts = [];
      const selectedShops = []; // 新增数组用于存储选中商品的店铺信息
      this.groupedCartProducts.forEach((shopGroup) => {
        shopGroup.products.forEach((product) => {
          if (product.isSelected) {
            selectedProducts.push({
              id: product.id,
              name: product.name,
              specification: product.specification,
              price: product.price,
              quantity: product.quantity,
              imgUrl: product.imgUrl,
              shopId: product.shopId, // 包含商品所属店铺id
              shopName: shopGroup.shopName // 包含商品所属店铺名称
            });
            // 将店铺信息添加到selectedShops数组，确保每个店铺信息只添加一次
            if (!selectedShops.some(shop => shop.shopId === product.shopId)) {
              selectedShops.push({
                shopId: product.shopId,
                shopName: shopGroup.shopName
              });
            }
          }
        });
      });

      const userId = this.getUserIdFromStorage(); // 从存储中获取用户id，这里假设你有相应的方法获取

      try {
        // 先将选中商品数量置为0
        for (let shopIndex = 0; shopIndex < this.groupedCartProducts.length; shopIndex++) {
          const shopGroup = this.groupedCartProducts[shopIndex];
          for (let itemIndex = 0; itemIndex < shopGroup.products.length; itemIndex++) {
            const product = shopGroup.products[itemIndex];
            if (product.isSelected) {
              product.quantity = 0;
              try {
                const response = await this.$axios.put(`http://localhost:3000/cart/${product.id}`, { quantity: 0 });
                console.log('商品数量已更新为0', response.data);
              } catch (error) {
                console.error('更新商品数量失败', error);
              }
            }
          }
        }

        const response = await this.$axios.post('http://localhost:3000/order', {
          userId,
          products: selectedProducts,
          shops: selectedShops, // 将选中商品的店铺信息传递到后端
          totalPrice: this.totalPrice,
          orderStatus: '待支付' // 初始状态为待支付
        });
        const orderData = response.data;
        uni.navigateTo({
          url: `/pages/order/orderis?orderId=${orderData.id}`
        });
      } catch (error) {
        console.error('创建订单失败', error);
        uni.showToast({
          title: '创建订单失败，请稍后重试',
          icon: 'none'
        });
      }
    },
    getUserIdFromStorage() {
      // 从存储中获取用户id的逻辑，这里简单返回一个示例值
      return '123456'; 
    }
  }
};
</script>

<style scoped>
/* 全局样式重置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
page {
  background-color: #f8f8f8;
}
.empty-cart-tip {
  text-align: center;
  font-size: 18px;
  color: #666;
  padding: 50px 0;
}

.cart-page {
  /* background-color: #f9f9f9; */
  padding: 20px;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  max-width: 800px;
  margin: 0 auto;
  padding-bottom: 60px;
}

.shop-group {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  margin-bottom: 25px;
  padding: 20px;
  transition: box-shadow 0.3s ease;
}

.shop-group:hover {
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.12);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.clear-cart {
  cursor: pointer;
  color: #888;
  text-decoration: none;
  transition: color 0.3s ease;
}

.clear-cart:hover {
  color: #ff5722;
}

.shop-name {
  font-size: 22px;
  color: #333;
  font-weight: 600;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.shop-total-price {
  color: #ff5722;
  font-size: 18px;
  font-weight: 600;
}

.cart-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 15px;
  transition: background-color 0.3s ease;
}

.cart-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.cart-item:hover {
  background-color: #fafafa;
}

.cart-item-image {
  width: 90px;
  height: 90px;
  border-radius: 10px;
  margin-right: 20px;
  object-fit: cover;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
}

.cart-item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.cart-item-name {
  font-size: 18px;
  color: #333;
  font-weight: 600;
  margin-bottom: 5px;
}

.price-container {
  display: flex;
  align-items: center;
}

.product-price {
  color: #ff5722;
  font-size: 18px;
  font-weight: 600;
  margin-right: 10px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 16px;
}

.quantity-container {
  display: flex;
  align-items: center;
  margin-top: 8px;
  justify-content: flex-end;
  /* 去除左右间距，让按钮紧凑 */
  padding: 0;
}

.quantity-container button {
  background-color: #f4f4f4;
  border: none;
  border-radius: 50%;
  width: 24px;
  height: 24px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0;
}

.quantity-container button:hover {
  background-color: #eaeaea;
}

.quantity-container button:disabled {
  background-color: #e0e0e0;
  cursor: not-allowed;
}

.cart-item-quantity {
  font-size: 14px;
  color: #666;
  margin: 0 5px;
}

.total-price-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 25px;
  border-top: 1px solid #eee;
  padding-top: 20px;
  padding: 15px;
  border-radius: 15px;
  position: fixed;
  margin: 13px;
  bottom: 60px;
  left: 0;
  right: 0;
  background-color: #f9f9f9;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  z-index: 101;
}

.total-price-text {
  font-size: 20px;
  color: #333;
}

.total-price {
  color: #ff5722;
  font-size: 24px;
  font-weight: 700;
}

.settlement-button {
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 5px 20px;
  cursor: pointer;
  font-size: 18px;
  transition: background-color 0.3s ease;
}

.settlement-button:hover {
  background-color: #007bff;
}

.active {
  background-color: #1890ff;
  color: white;
}

/* 修改多选和单选按钮样式 */
.header button,
.cart-item button {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: 1px solid #ccc;
  margin-right: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: transparent;
  cursor: pointer;
}

.header button.active,
.cart-item button.active {
  background-color: #1890ff;
  border-color: #1890ff;
}

.header button::after,
.cart-item button::after {
  content: '';
  display: none;
}

.header button.active::after,
.cart-item button.active::after {
  content: '';
  display: block;
  width: 10px;
  height: 10px;
  background-color: white;
  border-radius: 50%;
}


</style>